import { CITEXT } from "sequelize/types";
import { ScriptListService } from "../../service/scriptList";
import { ScriptModel } from "../../model/scriptList"
import UserService from "../../service/user";
import { GameService } from "../../service/game"
import { C, N} from "../../config/commonTypes"
import { log } from "console";
import { Restfull } from "../../config/resModel";
import { FsCon } from "../../utils/fsController"
import { LSFS } from "../../utils/LSFS";
import { errorTemRoom } from "../../config/resCodeMsg";
import {set,get ,del,client} from "../../redis";
class _GameCON {
  
    async createGame(ctx:C){
        // 发送用户id、创建时间戳组合成临时房间名字，存入reds中，设置有效时长30m
       
        // client.set('name', "hans",async function () {
        //     const name =  client.get("name");
        //     console.log("name", name);
        // });
        console.log("头部",ctx.userInfo);
        
        const { id } = ctx.userInfo;
        
        
        const { script_id,role } = ctx.request.body;
        console.log("创建房间的角色", role);
        const roomId = Date.now() + "." + id + "." + script_id;
        let _id = await get(id);
        if(_id){
            ctx.body = Restfull.faild(errorTemRoom);
            return
        }
        // 创建准备房间的id
        set(id,roomId);
        _id = await get(id);
        // 创建准备房间剧本详情，k：是房间id的value
        let scriptContent = {}
        set(roomId, JSON.stringify(role))
        ctx.body = Restfull.success({roomId:_id },"创建成功")
    }


    async overReadyGame(ctx:C) {
        const { id } = ctx.userInfo;
        //指向key对应的value，就是剧本游戏的key
        let id_value = (await get(id)) as string; 
          del(id);
          del(id_value);
          ctx.body = {
              code:200,
              msg:"已结束准备房间",
              data:{}
          }
    }

    async startGame(ctx:C) {
        const { players,game } = ctx.request.body;
        const { id } = ctx.userInfo
        let n = 0
      
       console.log("game", game);
       
       const serviceRes = await GameService.insertGame(game);
       let gameId = null;
    //    if(serviceRes.length == 1) {
            gameId = (serviceRes[0] as any).id
    //    }
       console.log("gameId",gameId);
       console.log("serviceRes", (serviceRes[0] as any).id);
       
       
       while(n<players.length){
        let res =   await UserService.updateUserInfo(players[n],{isGame: true,gameId,gameName:game.scriptName});
        console.log("resres", res);
          n++
     }

     //redis添加游戏记录
     const { scriptName,scriptId,role }  = game
     //整个剧本信息，公用线索分配
     const script = await ScriptListService.getScript(scriptId)
     //剧本名：scriptName，创建者：id，剧本id script_id
     const gameName  = game.scriptName + "." + gameId;
     let value = {
         scriptName,
         allClue: script.clue,
         role,
         dmId:id
     }
     //value 所有剧本信息，所有线索信息，分配线索信息
     set(gameName,JSON.stringify({data:value}))
       //增加一条游戏数
       ctx.body = Restfull.success({serviceRes:serviceRes[0]},"游戏开始成功111!")
    }


    async gameInfo(ctx:C) {
        console.log("query", ctx.query);
        
        const {gameId,scriptName} = ctx.query;
        console.log("gameId", gameId);
        
        // const res = await GameService.getGameInfo(gameId)
       let k = scriptName + '.' + gameId;
      let v = await get(k)
        ctx.body = Restfull.success({gameInfo:v},"查询成功")
        
    }

    //结束游戏
    async overGame(ctx:C) {
       
        const { players,gameId,scriptName } = ctx.request.body
        console.log("访问了",players,gameId);
        let n = 0;
       try {
            //清除redis
        del(`${scriptName}.${gameId}`)
        
        //改变数据库
        while(n<players.length){
            let res =   await UserService.updateUserInfo(players[n],{isGame: false});
            console.log("resres", res);
              n++
         }

         //改变数据库结束游戏

         const update = await GameService.updateGame(gameId,{isOver:true})

        ctx.body = Restfull.success({},"结束了")
       } catch(err) {
           console.log("err", err);
           ctx.body = Restfull.faild({code:500,msg:"结束游戏失败，请联系技术！"})
           
       }
    }


}


const GameCON = new _GameCON()

export {
    GameCON
}